﻿#include "TGAReadWrite.h"

#include "Output/Console.h"

bool WH::ReadTGA(const SPath &InFilePath, TVector<uint8_t> &OutData, ETextureFormat &OutFormat, uint64_t &OutWidth, uint64_t &OutHeight, uint64_t &OutPitch)
{
    //read TGA file
    auto Path8 = InFilePath.ToString().ToUtf8();
    FILE* File = fopen((const char*)Path8.Data(), "rb");
    if (!File)
    {
        WH::PrintLine(U"无法打开文件{}", InFilePath.ToString());
        return false;
    }

    //Read header
    uint8_t Header[18];
    fread(Header, 1, 18, File);

    //Read width and height
    OutWidth = *(uint16_t*)&(Header[12]);
    OutHeight = *(uint16_t*)&(Header[14]);

    //Read format
    uint16_t BitsPerPixel = *(uint16_t*)&(Header[16]);
    if (BitsPerPixel == 32)
    {
        OutFormat = ETextureFormat::R8G8B8A8;

        //Read data
        TVector<uint8_t> TempData;
        TempData.Resize(OutWidth * OutHeight * 4);
        fread(TempData.Data(), 1, TempData.Num(), File);

        OutPitch = OutWidth * 4;
        OutData.Resize(OutPitch * OutHeight);

        for (int i = 0; i < OutHeight; i++)
        {
            for (int j = 0; j < OutWidth; j++)
            {
                int TempRow = (OutHeight - i - 1); //upside down

                OutData[i * OutPitch + j * 4 + 0] = TempData[TempRow * OutWidth * 4 + j * 4 + 2];
                OutData[i * OutPitch + j * 4 + 1] = TempData[TempRow * OutWidth * 4 + j * 4 + 1];
                OutData[i * OutPitch + j * 4 + 2] = TempData[TempRow * OutWidth * 4 + j * 4 + 0];
                OutData[i * OutPitch + j * 4 + 3] = TempData[TempRow * OutWidth * 4 + j * 4 + 3];
            }
        }

    }
    else if(BitsPerPixel == 24)
    {
        //add alpha channel
        OutFormat = ETextureFormat::R8G8B8A8;

        TVector<uint8_t> TempData;
        TempData.Resize(OutWidth * OutHeight * 3);
        fread(TempData.Data(), 1, TempData.Num(), File);

        OutPitch = OutWidth * 4;
        OutData.Resize(OutPitch * OutHeight);

        for (int i = 0; i < OutHeight; i++)
        {
            for (int j = 0; j < OutWidth; j++)
            {
                int TempRow = (OutHeight - i - 1); //upside down

                OutData[i * OutPitch + j * 4 + 0] = TempData[TempRow * OutWidth * 3 + j * 3 + 2];
                OutData[i * OutPitch + j * 4 + 1] = TempData[TempRow * OutWidth * 3 + j * 3 + 1];
                OutData[i * OutPitch + j * 4 + 2] = TempData[TempRow * OutWidth * 3 + j * 3 + 0];
                OutData[i * OutPitch + j * 4 + 3] = 255;
            }
        }

    }

    else
    {
        WH::PrintLine(U"目前不支持{}位的TGA图片: {}", BitsPerPixel);
        return false;
    }



    fclose(File);
    return true;
}